package com.freesky.mobile.wechat.controller;

import com.alibaba.fastjson2.JSON;
import com.freesky.common.core.domain.AjaxResult;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * jsapi 演示接口的 controller.
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 * @date 2020-04-25
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/jsapi/{appid}")
public class WxJsapiController {

    //protected Logger logger = LoggerFactory.getLogger(getClass());

    private final WxMpService wxService;

    @RequestMapping("/getJsapiTicket")
    @ResponseBody
    public AjaxResult getJsapiTicket(@PathVariable String appid,
                                     @RequestParam("url") String url,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws WxErrorException {
        try {
            if(StringUtils.isNotEmpty(url)){
                url = StringEscapeUtils.unescapeHtml4(url);
            }
            //System.out.println(url);
            final WxJsapiSignature jsapiSignature = this.wxService.switchoverTo(appid).
                    createJsapiSignature(url);
            System.out.println("getJsapiTicket:"+ JSON.toJSONString(jsapiSignature));
            return AjaxResult.success("操作成功！",jsapiSignature);
        } catch (Exception ioe){
            return AjaxResult.error("系统异常,操作失败!");
        }
    }


}

